import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../bi.service';

@Component({
  selector: 'apes-newly-vip-analysis',
  templateUrl: './newly-vip-analysis.component.html',
  styleUrls: ['../door-tube-center-all.scss']
})
export class NewlyVipAnalysisComponent implements OnInit {
  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = window.innerHeight - 490 + 'px';

  endDate = null;      // 默认结束时间
  startDate = null;    // 默认开始时间 当天的前7天

  endTime = null;      // 传的结束时间
  startTime = null;    // 传的起始时间

  sevenData: any[];    // 曲线图相关

  // 饼图相关
  salesPieData: any;
  xinbao = [];
  xubao = [];
  xin: any;
  xu: any;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData:any;
  companyList: any[];

  startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  };
  endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  };


  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "日期", field: 'TJRQ'},
      {headerName: "VIP总数", field: 'VIPZS'},
      {headerName: "新增总数", field: 'XZZS'},
      {headerName: "年卡会员", field: 'XZNKHY'},
      {headerName: "保险会员", field: 'XZBXHY'},
      {headerName: "充值机油会员", field: 'XZJYHY'},
      {headerName: "储值会员", field: 'XZCZHY'},
      {headerName: "单位会员", field: 'XZDWHY'},
      // {headerName: "来源", field: ''}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (0 * 24 * 60 * 60 * 1000));
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this.submit();

  }

  submit() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.xinbao = [];
    this.xubao = [];
    this.xin = 0;
    this.xu = 0;
    // 传的时间 进行转换
    this.startTime = (this.startDate.toISOString()).slice(0, 10);
    this.endTime = (this.endDate.toISOString()).slice(0, 10);

    this.getTablesData();
  }

  getTablesData() {
    let data = { 'interfaceMethod': 'ipmMgzzForAppService.getXZVIPFX', 'pdata': { 'STARTDATE': this.startTime, 'ENDDATE': this.endTime, 'companyId': this.companyList} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            this.rowData = data;
            if( this.rowData.length === 0 ) {
              this.msg.info(`未找到满足条件的数据`);
            }
            data = data.sort(this.sortarr('TJRQ'));
            for (let i = 0, len = data.length; i < len; i++) {
              this.xinbao = (data[i].QVIPZS);
              this.xubao = (data[i].YHZS);
            }
            // 饼图 新保数据获取
            this.xin = this.xinbao;
            // 饼图 续保数据获取
            this.xu = this.xubao;
            //曲线图 数据获取
            const sevenList = data.slice(0, data.length);
            this.sevenData = sevenList.map((value) => {
              return { x: value['TJRQ'], y: value['XZZS'] };
            });
            // 加载 饼图
            this.salesPieData = this.getSalesTypePie();
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 饼图
  getSalesTypePie() {
    return [
      { x: 'VIP会员数', y: this.xin },
      { x: '总会员数', y: this.xu },
    ];
  }

// 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }
}

